package cn.minimelon.solon.service.clear.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.minimelon.solon.domain.ClearEvent;
import cn.minimelon.solon.domain.system.FusionInvoiceDetail;
import cn.minimelon.solon.domain.system.FusionOutBalanceDetail;
import cn.minimelon.solon.mapper.clear.FusionReportMapper;
import cn.minimelon.solon.service.clear.FusionReportService;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.solon.annotation.Db;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.event.EventBus;
import org.noear.solon.data.annotation.Tran;
import org.noear.solon.data.tran.TranPolicy;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class FusionReportServiceImpl implements FusionReportService {
    @Db("master")
    private FusionReportMapper fusionReportMapper;

    @Tran(policy = TranPolicy.never)
    @Override
    public void clearDetailOneYearAgo(String type) {
        long start = System.currentTimeMillis();
        String yearAgo = "2023-02-28 00:00:00";
        log.info("clearDetailOneYearAgo time:{}", yearAgo);
        if (StrUtil.equals(type, "invoice")) {
            for (int i = 0; i < 1; i++) {
                clearFusionInvoice(yearAgo, type);
            }
        } else if (StrUtil.equals(type, "balance")) {
            for (int i = 0; i < 2; i++) {
                clearFusionBalance(yearAgo, type);
            }
        }
        log.info("clearDetailOneYearAgo end parse: {} ms", System.currentTimeMillis() - start);
    }

    private void clearFusionBalance(String yearAgo, String type) {
        List<FusionOutBalanceDetail> streamData = fusionReportMapper.queryBalanceDetail(yearAgo);
        List<String> idList = new ArrayList<>();
        streamData.forEach(it -> {
            idList.add(it.getId());
        });
        ClearEvent clearEvent = new ClearEvent();
        clearEvent.setType(type);
        clearEvent.setIdList(idList);
        EventBus.publish(clearEvent);
    }

    private void clearFusionInvoice(String yearAgo, String type) {
        List<FusionInvoiceDetail> streamData = fusionReportMapper.queryInvoiceDetail(yearAgo);
        List<String> idList = new ArrayList<>();
        streamData.forEach(it -> {
            idList.add(it.getId());
        });
        List<List<String>> grList = ListUtil.split(idList, 500);
        for (List<String> gr : grList) {
            fusionReportMapper.deleteInvoiceDetail(gr);
            log.info("delete invoice count {}", gr.size());
        }
    }
}
